var System = {
    createdata  : {
        create  : function(to, id){ $(to).append("<div id='"+id+"'></div>"); },
        message : function(to, classe, msg, response){
        	$(to).append("<div class='"+classe+"' style='display:none;'>" +
		  			"<div>"+
		  			  "<div style='float:left'><h3>"+msg+"</h3></div>"+
		  			  "<div style='float:right; text-align: right;'>"+
		  			    "<div class='close'>"+
		  			      "<a href='javascript:void(0);' class='icoFechar' id='closeTopMessage'></a>"+
		  			    "</div>" +
		  			  "</div>" +
		  			"</div>"+
		  			"<div style='clear:both'>"+response+"</div>"+
		  		    "<ol></ol>" +
	  		    "</div>");
        	$('#closeTopMessage').click(function(){ $('div.'+ classe).hide(); });
        },
        modal   : function(to)
        {         	
        	$(to).append("<div id='modal-content'></div>"); 
        }
    },
    /*
     * Método que seta atributos ou altera estados de objetos
     */
    contextmenu:
    {
    	create: function(id, menu_json, append)
    	{
    		var menu = "<ul id='"+id+"' class='contextMenu'>";
    		
    		for(i in menu_json)
    		{
    			menu += "<li class='"+menu_json[i].icone+"'> <a href='#"+menu_json[i].url+"#"+menu_json[i].icone+"' id='"+menu_json[i].icone+"' >"+i+"</a></li>";
    		}
    		
    		menu += "</ul>";
    		
    		$(append).append(menu);

    	},
    	bind: function(append)
    	{
    		var tree	= $("#jtree").dynatree("getTree");
    		
    		tree.visit(function(e)
			{ 
    			if(e.data.menu != undefined)
				{
    				var menu_json = $.parseJSON(e.data.menu);
					System.contextmenu.create("myMenu"+e.data.key, menu_json, append);
					
					$("span."+e.data.addClass)
		    	      .destroyContextMenu() // unbind first, to prevent duplicates
		    	      .contextMenu({menu: "myMenu"+e.data.key}, 
		    	      function(action, el, pos) 
		    	      {
		    	    	  //eliminando o carregamento da pagina no activate.
//		    	    	  top.alteracao = true;
//		    	    	  top.load	= true;
		    	    	  
		    	    	  e.activate();
		    	    	  action = action.split('#');
		    	    	  
		    	    	  if(action[1] == 'delete')
		    	    		  System.contextmenu.remove(action[0], "System.setdata.reloadParentNode();");
		    	    	  else
		    	   	    	  System.loaddata.page(action[0], "#content-layout");
		    	    	
		    	      });
				}
			});
    	},
    	 remove: function(url, callback)
         {
         	$("#modal-content").html('<h3>Tem certeza que deseja remover este registro?</h3>');
         
         	System.modaldata.openDialog('#modal-content', 
         			{width: 400, 
         			modal:true, 
         			title: 'Remoção de dados',
         			resizable: false,
         			buttons: {
            				"SIM": function() {
			            		$.post(url, {
			                      }, 
			                      function(response) 
				                  {
			                    	  if(response.error)
			                    		  System.messagedata.alert('msgErro', msg, 'Error');
			                    	  else
			                    		  System.messagedata.alert('msgSucesso', 'Operação realizada com sucesso.', 'Sucesso');
			                    	  
			                    	  if(callback)
			                    		  eval(callback);
			                    	  
			                    	  System.modaldata.clearModal();
				                  }
			                  );
            				},
            				'NÃO': function() {
            					System.modaldata.clearModal();
            				}
         				}
         			});
         	return false;
         }
    },
    setdata : 
    {
    	tree: function (opts)
    	{
    		
    		if(opts.layout)
    			$('.ui-layout-'+opts.layout.append).append($('#jtree'));
    		
    		$("#jtree").dynatree({
    			  clickFolderMode: 1,
    			  persiste: true,
    			  cookieId: "dynatree", // Choose a more unique name, to allow multiple trees.
    			  cookie: {
    			  	expires: null // Days or Date; null: session cookie
    			  },
    		      onActivate: function(dtnode) 
    		      {
    				// alteração referente a verificação de alteração na tela.
    				var load = true;
    			
    				if(top.alteracao)
    				{
    					load = false;
    					if(!top.load){
	    					if(confirm("Existem alterações no formulário, deseja realmente sair?")) {
	    						top.alteracao = false;
	    						top.load = false;
	    						load = true;
	    					} else {
	    						top.load = true;
	    						load = false;
	    						top.node.focus();
	    			    		top.node.activate();
	    						return false;
	    					}
    					}
    				}
    				
    				if(load)
    				{
	    				if( dtnode.data.url ){
	    					// apago os editores
	    					System.formdata.destroyCkEditor();
	    					System.loaddata.page(dtnode.data.url, "#content-layout");
	    				}
    				}
    		      },
    		      onExpand: function(flag, node)
    		      {
    		    	  if(flag && node.data.isLazy)
    		    	  {
    		    		  node.reloadChildren();
    		    	  }
    		      },
    		      onClick: function(node, event) 
    		      {
    		          // Eat mouse events, while a menu is open
    		          if( $(".contextMenu:visible").length > 0 ){
    		            return false;
    		          }
    		        },
    		      strings: {
    		          loading: "Carregando…",
    		          loadError: "Erro ao carregar!"
    		      },
    		      initAjax: {
      		        url: opts.url_xml
    		      },
    		      onLazyRead: function(node){
    		          node.appendAjax({url: node.data.urlLazy,
                          data: {"key": node.data.key,
                                 "mode": "all"
                                 },
//                       dataType: "jsonp",
                         success: function(node) 
                     	{
                            setTimeout("System.contextmenu.bind('#context_menu')", 1000);
                         	
                         },
                         error: function(node, XMLHttpRequest, textStatus, errorThrown) {
                             // Called on error, after error icon was created.
                             },
                         cache: false // Append random '_' argument to url to prevent caching.

                         });
    		      	},
    		        dnd: {
    		            preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
    		            onDragStart: function(node) {
    		      			if(node.data.isFolder)
    		      				return false;
    		              /** This function MUST be defined to enable dragging for the tree.
    		               *  Return false to cancel dragging of node.
    		               */
    		              return true;
    		            },
    		            onDragEnter: function(node, sourceNode) {
    		              /** sourceNode may be null for non-dynatree droppables.
    		               *  Return false to disallow dropping on node. In this case
    		               *  onDragOver and onDragLeave are not called.
    		               *  Return 'over', 'before, or 'after' to force a hitMode.
    		               *  Return ['before', 'after'] to restrict available hitModes.
    		               *  Any other return value will calc the hitMode from the cursor position.
    		               */
    		              // Prevent dropping a parent below another parent (only sort
    		              // nodes under the same parent)
    		              if(node.parent !== sourceNode.parent)
    		                return false;
    		              // Don't allow dropping *over* a node (would create a child)
    		              return ["before", "after"];
    		              //return true;
    		            },
    		            onDrop: function(node, sourceNode, hitMode, ui, draggable) {
    		              /** This function MUST be defined to enable dropping of items on
    		               *  the tree.
    		               */
    		             
    		              sourceNode.move(node, hitMode);
    		              
    		              System.setdata.updateOrdem(node.data.urlOrdem, node.parent.data.key);
    		            }
    		          }
    		    });
    		
    	
    		$('#jtree').show();
    	},
    	updateOrdem: function(url, key)
    	{
    		var tree = $("#jtree").dynatree("getTree").getNodeByKey(key);
    	
    		var object = {ordem: []};//Criando o objeto JSON para mandar por POST
    		
    		//Convertendo o nó da arvore em objeto.
    		tree.toDict(true, function(e)
			{
    			var child	= $("#jtree").dynatree("getTree").getNodeByKey(e.key);
    			
				if(!e.isFolder)
				{
					if(child.isChildOf(tree))
					{
						var clean = e.key.split("_");
						//adicionando os valores ordenados ao JSON
						object.ordem.push(clean[1]);
					}
				}
			});
    		
    		$.post(url, object, function(response) {  });

    	},
    	createNode: function(content)
    	{
    		var node 	= $("#jtree").dynatree("getActiveNode");
			var tree	= $("#jtree").dynatree("getTree");
    		
    		if( node )
			{
    			if(node.data.isFolder)
				{
    				node.reloadChildren(function(node, isOk)
    				{
    				    if(!isOk) System.messagedata.alert('msgErro', 'Erro ao carregar os dados.', 'Error');
    				    else
    				    {
    				    	if(node.hasChildren() === true)
    		    			{
    				    		//limpando a execução de AJAX no EXPAND;
    				    		$("#jtree").dynatree({onExpand: function(){}});
    				    		//Expandindo o nó pai ATUAL e dando foco no filho criado
    			    			node.toggleExpand();
    			    			var newnode = tree.getNodeByKey(content.key);
    			    			newnode.focus();
    			    			newnode.activate();
    			    			//retornamos a execução de AJAX no EXPAND;
    				    		$("#jtree").dynatree({
    				    			onExpand: function(flag, node)
    				    			{
    				    				if(flag && node.data.isLazy)
    			    		    		  node.reloadChildren();
    			    		    	  
    				    				//System.setdata.toTip('a[title]');
    				    			}
    				    		});
    		    			}
    				    }
    				});
				}
    			else
    			{
    				node.parent.reloadChildren();
    				node.focus();
    			}
			}
    	},
    	removeNode: function()
    	{
    		var node = $("#jtree").dynatree("getActiveNode");
    		node.parent.reloadChildren();
    		node.parent.focus();
    		node.parent.activate();
    	},
    	reloadTree: function()
    	{
    		var tree = $("#jtree").dynatree("getTree");
    		tree.reload();
    	},
    	reloadNode: function()
    	{
    		var node = $("#jtree").dynatree("getActiveNode");
    		
    		node.reloadChildren(function(n, isOk)
    		{
    			if(n.hasChildren() === true)
    			{
    	    		//limpando a execução de AJAX no EXPAND;
    	    		$("#jtree").dynatree({onExpand: function(){}});
    	    		n.toggleExpand();
    	    		n.activate();
    			}
    			n.toggleExpand();
    		});
    		
    		node.focus();
    		node.activate();
    	},
    	reloadParentNode: function(filhos)
    	{
    		var node 	= $("#jtree").dynatree("getActiveNode");
    		node.parent.reloadChildren(function(newnode, isOk)
			{
    			var tem_revisao = '';
    			if(filhos)
        		{
        			var tem_revisao = '';
        			node.parent.toDict(true, function(e)
    				{
        				if(e.isFolder){
        					key_pai = e.key;
        					pai = $("#jtree").dynatree("getTree").getNodeByKey(e.key);
        					pai = pai.toDict();
        				}
        				
        				if(!e.isFolder)
        				{
        					if(e.addClass == 'revisao')
        						tem_revisao = 'revisao';
        				}
    				});
        		}
    			
				if(tem_revisao != ''){
					newnode.data.addClass = 'revisao';
				} else {
					newnode.data.addClass = 'folder';
				}
				newnode.render();
			});
    		
    		node.focus();
    		node.activate();
    	},
    	grid: function ()
    	{
    	
    	},
    	layout: function (opts)
		{
    		$('#jlayout').append("<div class='ui-layout-center' id='content-layout'></div>");
    		
    		for(i in opts.panels)
    			$('#jlayout').append("<div class='ui-layout-"+opts.panels[i]+"'></div>");
    		
    		$('#jlayout').layout({applyDefaultStyles: true});
		},
    	/*
    	 * Atribui ABAS às divs com classe .tabs
    	 */
        tab:      function(seletor){ $(seletor).tabs(); },
        /*
         * Atibui TOOLTIP (plugin qTip necessário) aos links com o ID especificado na function.
         */
        toTip: function(seletor)
        {
        	$(seletor).qtip({
        		position: {
        			my: 'top left',
        			target: 'mouse',
        			viewport: $(window), // Keep it on-screen at all times if possible
        			adjust: {
        				x: 10,  y: 10
        			}
        		},
        		hide: {
        			fixed: true // Helps to prevent the tooltip from hiding ocassionally when tracking!
        		},
        		style: 'ui-tooltip-jtools'
        	});
        }
    },
    /*
     * Método que controla formatação de conteúdo
     */
    formatdata : {
        even:       function(id , cor){$(id+":even").css("background-color", cor);},
        reloadTab: function(id)
        {
            var Jtab    = $('.tabs');
            Jtab.tabs('load', id);
        },
        number_format : function(number, decimals, dec_point, thousands_sep) {
        	
            var n = !isFinite(+number) ? 0 : +number, 
                prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
                sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
                dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
                s = '',
                toFixedFix = function (n, prec) {
                    var k = Math.pow(10, prec);
                    return '' + Math.round(n * k) / k;
                };
            // Fix for IE parseFloat(0.55).toFixed(0) = 0;
            s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
            if (s[0].length > 3) {
                s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
            }
            if ((s[1] || '').length < prec) {
                s[1] = s[1] || '';
                s[1] += new Array(prec - s[1].length + 1).join('0');
            }
           
            return s.join(dec);
        },
        removeAcento: function(text)
        {
          text = text.replace(new RegExp('[ÁÀÂÃ]','gi'), 'a');
          text = text.replace(new RegExp('[ÉÈÊ]','gi'), 'e');
          text = text.replace(new RegExp('[ÍÌÎ]','gi'), 'i');
          text = text.replace(new RegExp('[ÓÒÔÕ]','gi'), 'o');
          text = text.replace(new RegExp('[ÚÙÛ]','gi'), 'u');
          text = text.replace(new RegExp('[Ç]','gi'), 'c');
          text = text.replace(/ /g, "-");
          text = text.toLowerCase();
          return text;
        },
        mask : function(field, mask)
        {
            var array_to_mask   = new Array("cep", "date", "time", "cpf", "fone");
            var array_mask      = new Array("99999-999", "99/99/9999", "99:99", "999.999.999-99", "(99) 9999-9999");
            
            for(i in array_to_mask)
            {
                if(mask == array_to_mask[i])
                    $(field).mask(array_mask[i]);
            }
        }
    },
    messagedata : {
        clear: function ()
        {
    		$(".mensagem").html('');
        	$("div[class^='msg']").each(function(){ $(this).remove(); });
        },
        alert:  function(type, response, label, to)
        {
        	System.messagedata.clear();

        	var msg_to = "#mensagens";
        	
        	if(to) msg_to = to;
        	
        	System.createdata.message(msg_to, type, label, response);
        	
        	$('div.' + type).show().delay(5000).queue(function() {
        		$(this).hide();
        	});

        	$.scrollTo('body', 300);//Executa o scroll para a tela de mensagem
        },
        success: function(response, status, xhr, form)
        {
        	System.messagedata.alert('msgSucesso', response, 'Sucesso');
        }
    },
    modaldata : {
    	clearModal: function()
    	{
	        $('#modal-content').dialog('destroy');
	        $('#modal-content').dialog('close');
    	},
    	closeOnClick: function(seletor)
    	{
    		$(seletor).click(function(){ System.modaldata.clearModal(); return false; });
    	},
        onClick: function(id, type, params, static_content, params_post)
        {
    		var div_id	= "#modal-content";
    		var div_content = '#modal_body';

        	$(div_id).append('<div id="modal_message"></div>');
        	$(div_id).append('<div id="modal_body"></div>');
    		
            $("a[id="+id+"]").click(function()
            {
                if(!static_content){ $(div_content).load($(this).attr("href")); }
                else div_id	= static_content;
                
                if(type)
                {
                    if(type == "dialog")
                    {
                    	System.modaldata.openDialog(div_id, params);
                    	return false;
                    }
                }
            });
        },
        onChange: function(id, params, url_load)
        {
        	$(id).change(function()
            {
        		System.modaldata.loadDialog(params, url_load+'/id/'+$(this).val());
            });
        },
        loadDialog: function(params, url_load)
        {
        	var div_id	= "#modal-content";
        	$(div_id).append('<div id="modal_body"></div>');
            $("#modal_body").load(url_load);
            System.modaldata.openDialog(div_id, params);
            return false;
        },
        openDialog: function(id, params)
        {
            if($(id).dialog( 'isOpen' ) === false)
                $(id).dialog('open');
            else
            {
            	$(id).dialog( "destroy" );
            	$(id).dialog(params);
            }
        },
        openMidiaBox: function(id, is_gallery)
        {
        	var atb	= 'rel';
        	
        	if(!is_gallery) atb = 'id';
        	
        	$("a["+atb+"='"+id+"']").colorbox(
			        			{
			        				onOpen:function(){  },
			        				onLoad:function(){ },
			        				onComplete:function(){  },
			        				onCleanup:function(){  },
			        				onClosed:function(){ }
			        			}
        	);
        	return false;
        }
    },
/*TRATAMENTO DE FORMULARIOS - requer plugins validate, form, metadata*/
    formdata : {
       calendar:   function(params){$('.is_date_picker').datepicker(params);},
       save: function (message_type, is_ajax, callback, is_filter)
        {
    	   System.createdata.message("#mensagens", message_type[0], message_type[1], '');
           var container = $('div.'+message_type[0]);
           
    	   	var validator = $("form[name^='form_']").each(function()
            {
                $(this).validate({
                	invalidHandler: function(){ $.scrollTo('body', 300); },
                    errorContainer: container,
                    errorLabelContainer: $("ol", container),
                    wrapper: 'li',
                    submitHandler: function(form)
                    {
                	
                	try{ updateElementCK(); }catch(e){}
                	try{ System.formdata.updateCkEditor(); } catch(e){}
                	
                	var options ={
                            url: $(form).attr("action"),
                            type: 'post',
                            success:
                             function(response)
                             {
                                 try
                                  {
                                	  
                                	  if(callback)
                                	  {
                                		  	if(response.error)
	                                  		{
	                                  			  System.messagedata.alert('msgErro', response.error, 'Error');
	                                  			  return;
	                                  		}
                                		  	
                                		    eval(callback);
                                		    if(!is_filter)
                                		    	System.messagedata.alert('msgSucesso', 'Dados salvos com sucesso.', 'Sucesso');
                                	  }
                            		  else
			                      	  {
			                      		  if(response.error)
			                      		  {
			                      			  System.messagedata.alert('msgErro', response.error, 'Error');
			                      			  return;
			                      		  }	
			                      		  else
			                      		  {
			                      			  System.messagedata.alert('msgSucesso', 'Dados salvos com sucesso.', 'Sucesso');
			                      		  }
			                      	  }
                                  }
                                  catch(err)
                                  {
                                	  System.messagedata.alert('msgErro', 'Erro ao executar operação.', 'Erro');
                                	  return;
                                  }
                                  
                                  // alteração referente a verificação de alteração na tela.
                                  top.alteracao = false;
  	    						  //top.load = false;
  	    						  //load = true;
                             }
                        };

                        if(is_ajax)
                        {
                        	$(form).ajaxSubmit(options);
                        	return false;
                        }
                        else
                        {
                        	form.submit();
                        	return false;
                        }

                        return false;
                   }
                });
            });
        },
       saveUpload: function (form)
        {
    		$(form).ajaxForm({
				beforeSubmit: function()
				{
					$(form).validate(
					{
						errorClass: 'error',
	                    validClass: 'valid'
					});
					return $(form).valid();
				} ,
				dataType: 'script',
				success:   function(data){ 
					// alteração referente a verificação de alteração na tela.
                    top.alteracao = false;
				}
			});
        },
        validateUpload: function(form)
        {
        	form.validate();
        },
        remove: function(params, callback, to, seletor)
        {
        	if(seletor) seletor = seletor; else seletor = "a[id=delete]";
        	
            $(seletor).click(function()
            {
            	var url	= $(this).attr('href');
            	
            	$("#modal-content").html('<h3>Tem certeza que deseja remover este registro?</h3>');
            	
            	/**
            	 * Verifica se ha um atributo CALLBACK definido na TAG
	          	 * 
	          	 * Obs.: No caso de haver mais de uma grid com o botão de delete, por exemplo,
	          	 * é necessário definir o callback por atributo da TAG <A>, pois os callbacks parametrizados
	          	 * se sobreporiam um ao outro.
	          	 */
          	  	if($(this).attr('callback')!= undefined && $(this).attr('callback')!= "")
          	  		callback = $(this).attr('callback');
            	
            	System.modaldata.openDialog('#modal-content', 
            			{width: 400, 
            			modal:true, 
            			title: 'Remoção de dados',
            			resizable: false,
            			buttons: {
	            				"SIM": function() {
				            		$.post(url, {
				                      }, 
				                      function(response) 
					                  {
				                    	  if(response.error)
			                    		  {
				                    		  /** 
				                    		   * Tratamento de mensagem de erro de banco de dados
				                    		   * (o ideal é tratar o erro numa das camadas acima, mas não sendo possível,
				                    		   * esconde do usuário a mensagem gerada pelo SGBD)
				                    		   */
				                    		  if(response.error.indexOf('OCIStmtExecute') != -1)
				                    		  {
				                    			  var msg = 'Erro no acesso a base de dados.';
				                    		  }
				                    		  else
				                    		  {
				                    			  var msg = response.error;
				                    		  }
				                    		  System.messagedata.alert('msgErro', msg, 'Error');
			                    		  }
				                    	  else
				                    	  {
				                    		  if(callback)
				                    		  {
				                    			  eval(callback);
				                    		  }
				                    		  if(to)
		                      				  {
			                      				  $(to).html(response);
		                      				  }
				                    		  System.messagedata.alert('msgSucesso', 'Operação realizada com sucesso.', 'Sucesso');
				                    	  }
				                    	  System.modaldata.clearModal();
					                  }
				                  );
	            				},
	            				'NÃO': function() {
	            					System.modaldata.clearModal();
	            					//$( this ).dialog( "close" );
	            				}
            				}
            			});
            	return false;
            });
           
        },
        clear: function(seletor) {
        	var form = $("form[name^='form_']");
        	if(seletor)
        		form = $(seletor);
        	
        	form.each(function() {
        		$(this).find(':input').each(function() {
	                switch(this.type) {
	                    case 'password':
	                    case 'select-multiple':
	                    case 'select-one':
	                    case 'text':
	                    case 'textarea':
	                        $(this).val('');
	                        break;
	                    case 'checkbox':
	                    case 'radio':
	                        this.checked = false;
	                }
        		});
            });
        },
        getCkEditor: function ()
        {
        	var editor = $("textarea.has_editor").ckeditorGet();
        
        	return editor;
        },
        updateCkEditor : function ()
        {
        	$("textarea.has_editor").each(function(){
        		var editor = $(this).ckeditorGet();
        		editor.updateElement();
        	});
        },
        destroyCkEditor: function()
        {
        	try{
	        	for(var i in CKEDITOR.instances)
	        		CKEDITOR.remove(CKEDITOR.instances[i]);
        		}
        	catch(e){}
        },
        ckeditor: function()
        {
        	try
        	{
        		var ts = Math.round((new Date()).getTime() / 1000);
        		CKEDITOR.timestamp = ts;
        		$("textarea.has_editor").each(function()
        		{
        			$(this).ckeditor(function(t)
    				{
    				}, 
    				{ toolbar_Full :
    					[
    					    ['Source','-','NewPage','Preview','-','Templates'],
    						['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
    						['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
    						'/',
    						['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
    						['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
    						['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
    						['Link','Unlink','Anchor'],
    						['Table','HorizontalRule','SpecialChar','PageBreak'],
    						'/',
    						['Styles','Format', 'FontSize'],
    						['TextColor','BGColor'],
    						['Maximize', 'ShowBlocks']
    					]
    				});
        		});
        	}
        	catch(err)
        	{
        		System.messagedata.alert('msgErro', 'Não foi possível carregar o editor de texto.', 'Error');
        		return;
        	}
        },
        countText: function()
        {
        	$("textarea[counter], input[counter]").each(function()
        	{
        		var id_content	= "counter_"+$(this).attr('id');
        		
        		$(this).after("<div id='"+id_content+"'></div>");
        		
        		$(this).charCounter($(this).attr('counter'), {
            		container: "#"+id_content,
            		format: "%1 caracteres restantes"
            	});
        	});
        }
    },
    validatedata: 
    {
        countChecked: function(seletor, checkname, message)
        {
            $(seletor).click(function()
            {
            	if($("input[name='"+checkname+"']:checked").length == 0)
            	{
            		System.messagedata.alert('msgErro', message, 'Erro');
            		return false;
            	}
            });
        },
        checkSortable: function(to_validate)
        {
        	for(i in to_validate)
        	{
        		if($(to_validate[i]).sortable('toArray').length == 0)
        			System.messagedata.alert('msgErro', 'Selecione um '+i, 'Erro');;
        	}
        },
        /**
         * Verifica se o(s) campo(s) informado(s) por 'input' foi(foram) informados
         * @var input string|array seletor(es)
         * @var operator string - padrao 'AND'
         */
    	isEmpty: function(seletor, input, message, operator)
    	{
    		$(seletor).click(function()
    	    {
    			var ar_input = new Array();
    			
    			if( typeof(input) == 'string' )
    				ar_input.push(input);
    			else
    				var ar_input = input;
    			
    			var total_input = ar_input.length;
    			var total_erros = 0;
    			
    			for(var i = 0; i < total_input; i++)
    			{
    				if( $(ar_input[i]).val() == "" || $(ar_input[i]).val() == undefined )
    					total_erros++;
    			}
    			
    			if( operator == 'OR' )
    			{ // Basta que um dos campos esteja preenchido
    				if(  total_erros == total_input )
    				{
	    				System.messagedata.alert('msgErro', message, 'Erro');
	            		return false;
    				}
    			}
    			else // Padrao 'AND'
				{ // Todos os campos da lista vazios
    				if( total_erros > 0 )
    				{
    					System.messagedata.alert('msgErro', message, 'Erro');
                		return false;
    				}
				}
    	    });
    	}
    },
    /*
     * Método que executa carregamento de dados
     */
    loaddata : 
    {
        page: function(action, to, params, responseType, callback, msg_to)
        {
            $.post(action, params , function(response)
            {
            	
        		if(response.error){
        			System.messagedata.alert('msgErro', response.error, 'Error', msg_to);
        			return false;
        		}
        		else if(response.success)
        			System.messagedata.alert('msgSucesso', 'Operação realizada com sucesso.', 'Sucesso', msg_to);
        		else{
        			$(to).html(response);
        		}
        		
        		if(callback)
            		eval(callback);
            	
                return false;
            });
        },
        text: function(to, text){$(to).html(text);},
        html: function(to, html){$(to).html(html); $(to).focus();},
        click: function(seletor, to, params, responseType, callback, msg_to)
        {
            $("a[id='"+seletor+"']").click(function(){
            	if(to) to = to; else to = $(this).attr('rel');
            	
                System.loaddata.page($(this).attr("href"), to,  params, responseType, callback, msg_to);
                return false;
            });
        },
        clickAndChange: function(seletor, to, object, callback)
        {
        	$("a[id='"+seletor+"']").click(function()
        	{
        		params = {id: $(object).val(), content: $(object+" option:selected").text()};
        		
                System.loaddata.page($(this).attr("href"), to,  params, 'json', callback);
                return false;
            });
        },
        drop: function(action, object, callback)
        {
        	params = {id: object.item.attr('value'), ref: object.item.attr('ref'), content: object.item.text()};
        	
        	System.loaddata.page(action, null,  params, 'json', callback);
            return false;
        },
        attr: function(att, seletor, to, params)
        {
            $("a["+att+"='"+seletor+"']").click(function(){
            	if(to) to = to; else to = $(this).attr('rel');
                System.loaddata.page($(this).attr("href"), to);
                return false;
            });
        },
        change: function(id, to, url, callback)
        {
            $(id).change(function()
            {
            	var params = {id: $(this).val(), param: $(this).attr('param')};
            	System.loaddata.page(url, to, params, null, callback);
            	
                return false;
            });
        },
        blur: function(id, to, url, callback)
        {
            $(id).blur(function()
            {
            	var params = {id: $(this).val(), param: $(this).attr('param')};
            	System.loaddata.page(url, to, params, null, callback);
            	
                return false;
            });
        },
        jsonText: function(response, prefix, callback)
        {
        	for(i in response)
        	{
        		try{ 
        			var p = prefix+i;
        			
        			var content_to = $(p).get(0);
        			
        			if($("cke_" + p.replace('#','')))
        				$(prefix+i).val(response[i]);
        			else
        			{
	        			switch(content_to.tagName)
	        			{
	        				case "INPUT":
	        					$(prefix+i).val(response[i]);
	        				break;
	        				
	        				case "SELECT":
	        					$(prefix+i).val(response[i]);
	        				break; 
	        				
	        				case "SPAN":
	        				case "DIV":
	        				default:
	        					$(prefix+i).html(response[i]);
	        			}
        			}
        		} catch(e){}
        	}
        	
        	if(callback)
        		eval(callback);
        	
        },
        jsonSelect: function(response, seletor, selected, callback, attr)
        {
        	var selectElement = $(seletor);
        	selectElement.html('<option value="">- - Selecione - -</option>');
            $.each(response, function(index, value)
            {
            	if(attr)
            	{
            		option.setAttribute('conteudo', value);
            	}
            	
            	if ($.browser.msie) {
            		selectElement.append('<option value="'+index+'">'+value+'</option>');
            	}
            	else {
            		selectElement.append('<option value="'+index+'">'+value+'</option>', null);
            	}
            });
            
            if(selected)
            	selectElement.val(selected);
            
            if(callback)
        		eval(callback);
        },
        jsonSortable: function(response, prefix, content, not_multiselect)
        {
        	$(content).show();
        	
            for(i in response)
            {
            	var selectElement = $(prefix+i);
            	
            	selectElement.find('option').remove();//limpando o multiselect
            	
            	if(not_multiselect)
            		selectElement.append('<option value="">-- Selecione --</option>');
            	
            	for(k in response[i])
            	{
            		if(response[i][k].id != undefined)
            		{
            			//selectElement.addClass('required');//Tornando o campo obrigatório
            			
	            		if ($.browser.msie) {
	                		selectElement.append('<option value="'+response[i][k].id+'">'+response[i][k].descricao+'</option>');
	                	}
	                	else {
	                		selectElement.append('<option value="'+response[i][k].id+'">'+response[i][k].descricao+'</option>', null);
	                	}
            		}
            	}
            }
            
            if(not_multiselect == undefined)
        	{
            	$('.multiselect').multiselect();
                $('.multiselect').multiselect('clearAvailable');
        	}
            
        }
    },
    ajaxdata:
	{
        control:    function()
        {
    		$('body').append('<div id="loading"></div>');
    		$("#loading").hide().css({
    			'z-index': '99999',
    			position: "fixed",
    			background : "#DF0000",
    			color: "#fff",
    			padding: "5px",
    			width: "150px",
    			top: "0",
    			left: "45%"
    		}).html('Aguarde carregando...');
    		$('body').ajaxStart(function(){ $("#loading").show(); });
    		$('body').ajaxStop(function(){ $("#loading").hide(); });
        }
	},
    showdata : 
    {
        change: function(id, div)
        {
            $(id).change(function()
            {
                if($(this).val() == "true") {$(div).show();}
                else{$(div).hide();}
            });
        },
        changeToogle: function(id, content, prefix)
        {
        	$(content+"[id^='"+prefix+"']").hide();
        	
            $(id).change(function()
            {
            	$(content+"[id^='"+prefix+"']").hide();
            	
            	$(content+"[id^='"+prefix+"']").find('select').each(function(){ $(this).val(''); });
            	
            	$('#'+prefix+$(this).val()).show();
            });
        },
        click: function(id)
        {
            $(id).each(function(){
            	$(this).click(function()
	            {
            		var div_id	= $(this).attr('rel');
            		
	                $("#"+div_id).toggle();
	                return false;
	            });
            });
        },
        hover:  function(id, div, sub)
        {
            $(id).hover(function() {$(div).show();});
            $(div).hover(function(){}, function(){$(this).hide();});
        },
        toggle: function(id, suffix)
    	{
    	 	$("input[name='"+id+"']").each(function()
    	 	{
    	 		var previo 	= $(this).prev().val();
	 			var proximo	= $(this).next().val();
	 			var atual	= $(this).val();
	 			
    	 		if(this.checked)
    	 			$('#'+atual+'_'+suffix).show();
    	 		
    	 		$(this).click(function()
    	 		{
    	 			$('#'+atual+'_'+suffix).show();
    	 			
    	 			if(previo != "undefined")
    	 				$('#'+previo+'_'+suffix).hide();
    	 			if(proximo != "undefined")
    	 				$('#'+proximo+'_'+suffix).hide();
    	 		});
    	 	});
    	}
     },
     griddata:
     {
     	dataTable: function(url, columns, language, extra_data)
     	{
 	    	 $('#dataTable').dataTable({
 	 			"bJQueryUI": true,
 	 			"sPaginationType": "full_numbers",
 	 			"oLanguage": {
 	 				"sUrl": BASEURL + "/CreatixLibPlugin/js/dataTable/support/pt_BR.txt"
 	 			},
 	 			"bProcessing": false,
 	 			"iDisplayLength": 1,
 	 			"bLengthChange": false,
 	 			"bServerSide": true,
 	 	        "bRetrieve": true,
 	 			"sAjaxSource": url,
 	 			"aoColumnDefs": [{"bSortable": false, "aTargets": [columns.length - 1]}],
 	 			"aoColumns": columns,
 	 			"fnServerParams": function ( aoData ) {
 	 				//console.log(JSON.stringify(extra_data));
 	 				if(extra_data)
 	 				{
 	 					for(i in extra_data)
 	 						aoData.push( extra_data[i] );
 	 				}
 	 		    },
 	 			"fnInitComplete": function(oSettings, json) {
 	 	            System.griddata.remove();
 	 	            $('.dataTables_filter input').attr('placeholder', 'Pesquisar...');
 	 	        }
 	 		});
 	    	
     	},
     	dataTableDefault: function()
     	{
 	    	 $('#dataTable').dataTable({
 	 			"bJQueryUI": true,
 	 			"sPaginationType": "full_numbers",
 	 			"oLanguage": {
 	    		    "sUrl": BASEURL + "/CreatixLibPlugin/js/dataTable/support/pt_BR.txt"
 	 			},
 	    	 	"aaSorting": [ [0,'desc'], [1,'asc'] ]
 	 		});
     	},
     	remove: function()
     	{
                 $("a.delete").click(function()
                 {
                 	var url	= $(this).attr('href');
                 	
                 	$("#modal-content").html('<h3>Tem certeza que deseja remover este item?</h3>');
                 	
                 	System.modaldata.openDialog('#modal-content', 
                 			{width: 400, 
                 			height: 120, 
                 			modal:true, 
                 			title: 'Remoção de dados',
                 			resizable: false,
                 			buttons: {
			         				'Cancelar': function() {
			     					$( this ).dialog( "close" );
			     				},
     	            				"Remover": function() {
     				            		$.post(url, {
     				                      }, function(response) 
     					                      {
                                                     System.messagedata.alert('Sucesso', 'Operação realizada com sucesso.', 'Sucesso');
                                                     System.modaldata.clearModal();
     					                      }
     				                      );
     	            				}
                 				}
                 			});
                 	return false;
                 }
                 );
     	}
     }
};
//Iniciamos a validação de AJAX

$(document).ready(function(){ 
	System.ajaxdata.control(); 
	System.formdata.calendar();
});